#!/usr/bin/env python3
"""
Direct test of MCP components without LLM.

This script tests the forecast analyzer directly to ensure
calculations are working correctly.
"""

import asyncio
import sys
import json
sys.path.insert(0, '..')

from src.mcp.forecast_client import ForecastAPIClient
from src.mcp.forecast_analyzer import ForecastAnalyzer


async def main():
    """Test MCP components."""
    print("="*80)
    print("🧪 测试水文预报分析器（不使用LLM）")
    print("="*80)
    
    # 1. Load data
    print("\n📂 加载数据...")
    client = ForecastAPIClient()
    
    try:
        # Try loading from local file first
        data = client.load_local_data("../data/model_exec.json")
        print("✅ 成功从本地文件加载")
    except FileNotFoundError:
        print("⚠️  本地文件不存在，尝试从API获取...")
        session_id = "daa0d8a6-dfb3-4887-b798-366f4682c453"
        data = await client.fetch_forecast_data(session_id)
        print("✅ 成功从API获取")
    
    # 2. Initialize analyzer
    print("\n🔬 初始化分析器...")
    analyzer = ForecastAnalyzer(data)
    print("✅ 分析器初始化完成")
    
    # 3. Test session info
    print("\n" + "="*80)
    print("📋 测试1: 获取会话信息")
    print("="*80)
    session_info = analyzer.get_session_info()
    print(json.dumps(session_info, ensure_ascii=False, indent=2))
    
    # 4. Test model parameters
    print("\n" + "="*80)
    print("⚙️  测试2: 获取模型参数")
    print("="*80)
    model_params = analyzer.get_model_parameters()
    print(f"模型名称: {model_params.get('model_name')}")
    print(f"模型类型: {model_params.get('model_type')}")
    print(f"初始状态: SA0={model_params.get('initial_state', {}).get('SA0')}, "
          f"UA0={model_params.get('initial_state', {}).get('UA0')}, "
          f"YA0={model_params.get('initial_state', {}).get('YA0')}")
    print(f"参数数量: {len(model_params.get('parameters', {}))}")
    
    # 5. Test real forecast analysis
    print("\n" + "="*80)
    print("📊 测试3: 分析真实预报")
    print("="*80)
    real_analysis = analyzer.analyze_real_forecast()
    metrics = real_analysis['metrics']
    
    if 'error' in metrics:
        print(f"❌ 错误: {metrics['error']}")
    else:
        print(f"✅ 洪量: {metrics['flood_volume_m3']:,.2f} m³")
        print(f"✅ 洪峰流量: {metrics['peak_discharge_m3s']:.2f} m³/s")
        print(f"✅ 峰现时间: {metrics['peak_time']}")
        print(f"✅ 平均流量: {metrics['avg_discharge_m3s']:.2f} m³/s")
        print(f"✅ 数据点数: {metrics['num_points']}")
        print(f"✅ 预报时段: {metrics['start_time']} 至 {metrics['end_time']}")
    
    # 6. Test hypothetical forecasts
    print("\n" + "="*80)
    print("🔮 测试4: 分析假拟预报")
    print("="*80)
    hyp_analyses = analyzer.analyze_all_hypothetical()
    print(f"假拟预报数量: {len(hyp_analyses)}")
    
    for i, hyp in enumerate(hyp_analyses[:3]):  # Show first 3
        print(f"\n假拟预报 #{i} ({hyp.get('name', 'N/A')}):")
        metrics = hyp['metrics']
        if 'error' in metrics:
            print(f"  ❌ 错误: {metrics['error']}")
        else:
            print(f"  洪量: {metrics['flood_volume_m3']:,.2f} m³")
            print(f"  洪峰: {metrics['peak_discharge_m3s']:.2f} m³/s")
            print(f"  峰现时间: {metrics['peak_time']}")
    
    if len(hyp_analyses) > 3:
        print(f"\n... 还有 {len(hyp_analyses) - 3} 个假拟预报")
    
    # 7. Test comparison
    print("\n" + "="*80)
    print("🔍 测试5: 对比分析")
    print("="*80)
    comparison = analyzer.compare_forecasts()
    
    if 'error' in comparison:
        print(f"❌ 错误: {comparison['error']}")
    else:
        print(f"✅ 对比完成，共 {comparison['num_hypothetical']} 个假拟预报")
        
        # Show summary
        summary = comparison['summary']
        if 'note' not in summary:
            print("\n统计摘要:")
            print(f"  洪量差异范围: {summary['volume_diff_range']['min_percent']:.2f}% ~ "
                  f"{summary['volume_diff_range']['max_percent']:.2f}% "
                  f"(平均: {summary['volume_diff_range']['avg_percent']:.2f}%)")
            print(f"  洪峰差异范围: {summary['peak_diff_range']['min_percent']:.2f}% ~ "
                  f"{summary['peak_diff_range']['max_percent']:.2f}% "
                  f"(平均: {summary['peak_diff_range']['avg_percent']:.2f}%)")
        
        # Show first comparison
        if comparison['comparisons']:
            comp = comparison['comparisons'][0]
            print(f"\n示例对比 ({comp['name']}):")
            diff = comp['differences']
            print(f"  洪量差异: {diff['flood_volume']['difference_m3']:+,.2f} m³ "
                  f"({diff['flood_volume']['difference_percent']:+.2f}%)")
            print(f"  洪峰差异: {diff['peak_discharge']['difference_m3s']:+.2f} m³/s "
                  f"({diff['peak_discharge']['difference_percent']:+.2f}%)")
    
    # Summary
    print("\n" + "="*80)
    print("✅ 所有测试完成！")
    print("="*80)
    print("\n💡 提示:")
    print("  - 如需使用LLM Agent，运行: python hydrology_forecast_agent.py")
    print("  - 查看完整文档: ../docs/MCP_HYDROLOGY.md")


if __name__ == "__main__":
    asyncio.run(main())

